<template>
  <transition
    name="m-messageA-fade"
    @before-leave="handleClose"
    @after-leave="$emit('destrory')"
  >
    <div v-show="visible" class="m-messageA" :class="clazz" :style="comStype">
      {{ message }}
    </div>
  </transition>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  getCurrentInstance,
  onMounted,
  onUnmounted,
  PropType,
  ref,
} from "vue";
import type { MessageType } from "./messageA.type";
export default defineComponent({
  name: "MMessageA",
  props: {
    type: {
      type: String as PropType<MessageType>,
      default: "",
    },
    message: String,
    durantion: {
      type: Number,
      default: 2000,
    },
    center: {
      type: Boolean,
      default: true,
    },
    onClose: {
      type: Function,
    },
    offset: {
      type: Number,
      default: 20,
    },
    zIndex: {
      type: Number,
      default: 999,
    },
    show: {
      type: Boolean,
      default: undefined,
    },
  },

  setup(props) {
    const _visible = ref(false);
    const visible = computed(() => {
      if (props.show != undefined) {
        return props.show;
      }
      return _visible.value;
    });
    const clazz = computed(() => {
      return [`m-messageA--${props.type}`, props.center ? "is-center" : ""];
    });

    const comStype = computed(() => {
      return {
        top: props.offset + "px",
        zIndex: props.zIndex,
      };
    });

    const handleClose = () => {
      if (props.onClose) {
        props.onClose();
      }
    };
    let timer = null;
    const startTimer = () => {
      setTimeout(() => {
        _visible.value = false;
      }, props.durantion);
    };

    onMounted(() => {
      _visible.value = true;
      if (props.show == undefined) {
        startTimer();
      }
    });

    onUnmounted(() => {
      clearTimeout(timer);
    });

    return {
      comStype,
      clazz,
      visible,
      handleClose,
    };
  },
});
</script>
